import java.util.*;

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int x) {
        val = x;
    }

    public TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        List<List<Integer>> res = new ArrayList<>();
        if (root != null) queue.add(root);
        boolean leftToRight = true;
        while (!queue.isEmpty()) {
            int size = queue.size();
            ArrayList<Integer> temp = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                root = queue.poll();
                temp.add(root.val);
                if (root.left != null) queue.add(root.left);
                if (root.right != null) queue.add(root.right);
            }
            if (!leftToRight) Collections.reverse(temp);
            leftToRight = !leftToRight;
            res.add(temp);
        }
        return res;
    }

    public static void main(String[] args) {
        TreeNode t17 = new TreeNode(7, null, null);
        TreeNode t15 = new TreeNode(15, null, null);
        TreeNode t20 = new TreeNode(20, t15, t17);
        TreeNode t9 = new TreeNode(9, null, null);
        TreeNode t3 = new TreeNode(3, t9, t20);
        System.out.println(new Solution().levelOrder(t3));
    }
}

